<template>
  <div>
    <a-form :model="form" ref="formRef" :rules="rules">
      <a-form-item label="姓名" name="name">
        <a-input v-model:value="form.name" />
      </a-form-item>
      <a-form-item label="电话" name="phone">
        <a-input v-model:value="form.phone" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import router from "@router/index.js";
import { reactive, ref, toRefs } from "@vue/reactivity";
import { $Storage } from "@utils/storage.js";
import {register} from "@apis/register.js"
import $http from "@utils/request.js"
import {wxLogin} from "@apis/login.js"

export default {
  setup() {
    const state = reactive({
      openid: "", //判断小程序项目还是pc项目
      unionid: "", //统一标识符
      form: {
        name: "",
        phone: "",
      },
      rules: {
        name: [
          {
            required: true,
            message: "请填写用户名称",
            trigger: "change",
          },
        ],
        phone: [
          {
            required: true,
            message: "请填写电话号码",
            trigger: "change",
          },
        ],
      },
    });

    const { isRegister } = router.currentRoute.value.query;

    if (isRegister === "1") {
      //已经注册
      const { token } = router.currentRoute.value.query;
      $Storage.setItem("jwttoken", token);
      router.push("/home");
    } else {
      //未注册
      const { openid, unionid } = router.currentRoute.value.query;
      state.openid = openid;
      state.unionid = unionid;
    }

    // 注册接口
    const API_register = (data)=>{
        return $http.request({
                url:register,
                method:"POST",
                data:{
                    data
                    
                }
            })
    }

    // 登录接口
    const API_wxLogin = (param)=>{
        $http.request({
            url:wxLogin,
            method:"POST",
            data:{
                param
            }
        })
    }

    // 注册
    const formRef = ref();
    const onSubmit = () => {
      formRef.value
        .validate()
        .then(async() => {
            let data = {
                name:state.form.name,//用户名
                phone:state.form.phone,//电话号码
                pcopenid:state.openid,//判断小程序项目还是pc项目
                wxuid:state.unionid,//统一资源标识符
            }
            let resReigster = await API_register(data)

            if(resReigster.data.code === 1000){
                let data = {
                    pcopenid:state.openid,//判断小程序项目还是pc项目
                    wxuid:state.unionid,//统一资源标识符
                }
                let resLogin = await API_wxLogin(data)
                console.log(resLogin)
            }
        })
        .catch((error) => {
          console.log("error", error);
        });
    };


    


    return {
      ...toRefs(state),
      formRef,
      onSubmit,
    };
  },
};
</script>

<style>
</style>